package com.example.daily.demo.task;

import com.example.daily.demo.config.SendMailSmtp;
import com.example.daily.demo.config.ShowMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;


import java.util.List;


@EnableScheduling  //用于定义在配置类上，用于开启定时任务的支持 ，是方法上的注解@Scheduled的前提
@Configuration
public class MailTask {

    @Autowired
    ShowMail showMail;

    @Autowired
    SendMailSmtp sendMailSmtp;


    @Scheduled(cron =" 0 0/20 * * * ?")
    public void   EMailTask() throws Exception{
        // 1.获取目标邮箱的收件箱
        List<ShowMail> res =  showMail.imapReceive();

        if (res!=null && res.size() > 0){// 有未读邮件
            for (ShowMail re : res) {
                // 2.拿出未读的邮件（得到相应的参数）
                System.out.println("主题:　" + re.getSubject());
                System.out.println("收信人地址:　" + re.getToUsernames());
                System.out.println("正文内容:　" + re.getContent());
                // 3.根据相应参数，发送邮件
                String str = re.getToUsernames().substring(re.getToUsernames().indexOf("<")+1,  re.getToUsernames().indexOf(">"));
                System.out.println(str);
                sendMailSmtp.sendHtmlMail( str.split(","), re.getSubject(),"收到");
            }
        }
    }
}
